
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:steam_app/config/app_routes.dart';
import 'package:steam_app/config/app_theme.dart';
import '../../data/user_product_repository.dart';
import '../../provider/user_provider.dart';
import '../library/library_page.dart';
import '../widgets/user_avatar.dart';


class UserPage extends StatefulWidget {
  const UserPage({super.key});

  @override
  State<UserPage> createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  int _gameCount = 0; //用户游戏数量
  final UserProductRepository _userProductRepo = UserProductRepository();

  @override
  void initState() {
    super.initState();
    _loadUserLibraryCount();
  }

  Future<void> _loadUserLibraryCount() async {
    final user = context
        .read<UserProvider>()
        .currentUser;
    if (user != null) {
      final games = await _userProductRepo.getLibraryGamesForUser(user.id);
      if (mounted) {
        setState(() {
          _gameCount = games.length;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final user = context
        .watch<UserProvider>()
        .currentUser;

    if (user == null) {
      return const Scaffold(
        body: Center(child: Text('未登录')),
      );
    }

    return Scaffold(
      backgroundColor: pageBackgroundColor,
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: 50),
            _buildHeader(user),
            const SizedBox(height: 16),
            _buildStats(user),
            const SizedBox(height: 12),
            _buildAddFriendButton(),
            const SizedBox(height: 16),
            _buildContentSection(),
            const SizedBox(height: 16),
            _buildSettings(context, user),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader(user) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: Row(
        children: [
          UserAvatar(
            user: user,
            radius: 32,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  user.name,
                  style: const TextStyle(color: textColor,
                      fontSize: titleFontSize,
                      fontWeight: titleFontWeight),
                ),
                const SizedBox(height: 4),
                OutlinedButton(
                  onPressed: () {
                    //无功能
                  },
                  style: OutlinedButton.styleFrom(
                    foregroundColor: textColor,
                    side: const BorderSide(color: dimTextColor),
                  ),
                  child: const Text('查看个人资料'),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildStats(user) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: hPaddingSize),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildStatItem(
            '$_gameCount',
            '游戏',
            onTap: () {
              //点击时，推入LibraryPage页面
              Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const LibraryPage()),
              );
            },
          ),
          _buildStatItem('11', '好友'), //固定数值，且不可点击（ontap=null）
          _buildStatItem('¥${user.balance.toStringAsFixed(2)}', '钱包'), //不可点击（ontap=null）
        ],
      ),
    );
  }

  Widget _buildStatItem(String value, String label, {VoidCallback? onTap}) {
    return GestureDetector(
      onTap: onTap, //如果onTap不为 null，则此组件可点击
      child: Container(
        //添加背景色以扩大点击区域，并使其在点击时无视觉效果
        color: Colors.transparent,
        child: Column(
          children: [
            Text(
              value,
              style: const TextStyle(
                color: textColor,
                fontSize: 18,
                fontWeight: titleFontWeight,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              label,
              style: const TextStyle(color: dimTextColor, fontSize: 14),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAddFriendButton() {
    return ElevatedButton.icon(
      onPressed: () {
      },
      style: ElevatedButton.styleFrom(
        backgroundColor: blueButtonColor,
        foregroundColor: textColor,
        padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 12),
      ),
      icon: const Icon(Icons.person_add_alt_1),
      label: const Text('添加好友'),
    );
  }

  Widget _buildContentSection() {
    final items = [
      '好友动态',
      '好友',
      '组',
      '截图/视频',
      '徽章',
      '库存',
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: items.map((label) {
        return ListTile(
          title: Text(label, style: const TextStyle(color: textColor)),
          trailing: const Icon(Icons.chevron_right, color: dimTextColor),
          onTap: () {
            /*无功能*/
          },
        );
      }).toList(),
    );
  }

  Widget _buildSettings(BuildContext context, user) {
    return Column(
      children: [
        const Divider(color: dimTextColor),
        ListTile(
          title: const Text('账户明细', style: TextStyle(color: textColor)),
          subtitle: const Text(
              '商店、安全、家庭', style: TextStyle(color: dimTextColor)),
          trailing: const Icon(Icons.chevron_right, color: dimTextColor),
          onTap: () {},
        ),
        ListTile(
          title: const Text('更改账户', style: TextStyle(color: textColor)),
          subtitle: Text(
              user.account, style: const TextStyle(color: dimTextColor)),
          trailing: const Icon(Icons.chevron_right, color: dimTextColor),
          onTap: () {},
        ),
        ListTile(
          title: const Text('退出', style: TextStyle(color: errorColor)),
          onTap: () {
            Provider.of<UserProvider>(context, listen: false).logout();
            Navigator.pushReplacementNamed(context, login_page);
          },
        ),
      ],
    );
  }
}

